const mysql = require("mysql");
const $dbConfig = require("./dbconfig.js"); //注意改成自己项目中的路径
const sql = require("./sql.js");
const pool = mysql.createPool($dbConfig); // 使用连接池


  let paramList = (obj) => {
    let paramArr = [];
    for (let key in obj) {
      if (obj[key]) {
        paramArr.push(obj[key]);
      }
    }
    return paramArr;
  };

// 增
let dbAdd = (table, req, res, next) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      let paramValue = paramList(req);
      connection.query(sql[table].insert(...paramValue), (err, result) => {
        if (err) {
          reject(err);
        }
        resolve(result);
        connection.release();
      });
    });
  });
};
// 删
let dbDelete = (table, req, res, next) => {
  let paramValue = paramList(req);
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      connection.query(sql[table].delete, [...paramValue], (err, result) => {
        if (err) {
          reject(err);
        }
        resolve(result);
        connection.release();
      });
    });
  });
};
// 改
let dbUpdate = (table, req, res, next) => {
  let paramValue = paramList(req);
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      connection.query(sql[table].update, [...paramValue], (err, result) => {
        if (err) {
          reject(err);
        }
        resolve(result);
        connection.release();
      });
    });
  });
};
// 查一个
let dbQueryById = (table, req, res, next) => {
  let paramValue = paramList(req);
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      connection.query(sql[table].queryById, [...paramValue], (err, result) => {
        if (err) {
          reject(err);
        }
        resolve(result);
        connection.release();
      });
    });
  });
};

//   查全部
let dbQueryAll = (table, req, res, next) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      connection.query(sql[table].queryAll, (err, result) => {
        if (err) {
          reject(err);
        }
        resolve(result);
        connection.release();
      });
    });
  });
};

let db = {
  dbAdd,
  dbDelete,
  dbUpdate,
  dbQueryById,
  dbQueryAll,
};

module.exports = db;
